<template>
  <view class="page-body">
    <view class="content">
      <div class="flex flex-col items-center justify-center m-b-29">
        <!-- <image :src="logoRow" style="width: 222rpx" mode="widthFix" /> -->
        <image :src="title_text" class="title_text_img" mode="widthFix" />
      </div>
      <up-form labelWidth="0" :model="formData" :rules="rules" ref="formRef">
        <up-form-item prop="merchantId" class="m-b-22">
          <!-- <WSelect
            class="w-select"
            v-model="formData.merchantId"
            :list="merchantList"
            placeholder="请选择绑定门店"
            @change="changeMerchantId"
          >
            <template #icon>
              <div class="iconfont icon-mendian"></div>
            </template>
          </WSelect> -->
          <w-select
            style="width: 100%"
            v-model="formData.merchantId"
            placeholder="请选择绑定门店"
            width="100%"
            height="53.33rpx"
            filterable
            :list="merchantList"
            @change="changeMerchantId"
          >
            <template #icon>
              <div class="iconfont icon-mendian m-l-9 m-r-9"></div>
            </template>
          </w-select>
        </up-form-item>
        <up-form-item prop="posNo" class="m-b-22">
          <div class="flex-1 w-0">
            <up-input
              style="height: 53.33rpx"
              v-model="formData.posNo"
              placeholder="请输入POS机号"
              maxlength="4"
              @blur="posNoBlur"
              type="number"
            >
              <template #prefix>
                <div class="iconfont icon-shebei"></div>
              </template>
            </up-input>
            <div v-if="posNoSuccess" class="pos-no-success">POS机号可用</div>
          </div>
        </up-form-item>
        <up-form-item prop="snNo" class="m-b-22">
          <up-input
            style="height: 53.33rpx"
            v-model="formData.snNo"
            placeholder="请输入设备SN号"
            :disabled="Boolean(commonStore.snNo)"
          >
            <template #prefix>
              <div class="iconfont icon-SN"></div>
            </template>
          </up-input>
        </up-form-item>
        <up-button class="m-t-27 submit_bt" type="primary" @click="submit">
          确认绑定
        </up-button>
      </up-form>
    </view>
  </view>
</template>
<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
import title_text from "@/static/images/title_text.png";
import utils from "@/utils/index.js";
import allApi from "@/api/index.js";
import { trim } from "lodash-es";
import { useCommonStore } from "../../store/common";
const commonStore = useCommonStore();

const formRef = ref();
const formData = ref({
  posNo: "", //POS机号
  deviceType: 1, //设备类型
  snNo: "", //设备SN号
  merchantId: "", //门店编号
  merchantName: "", //门店名称
  deviceModel: "", //设备型号
  deviceManufacturer: "", //设备厂商
  appVersion: "", //APP版本号
  sysVersion: "", //系统版本
  homeScreen: "", //主屏幕尺寸
  secondaryScreen: "", //副屏幕尺寸
  authId: "", //租户id
});
const rules = reactive({
  merchantId: {
    type: "string",
    required: true,
    message: "请选择绑定门店",
    trigger: ["change"],
  },
  posNo: [
    {
      trigger: ["blur"],
      validator: async (rule, value, callback) => {
        if (!formData.value.merchantId)
          return callback(new Error("请先选择绑定门店"));
        if (!trim(value).length) return callback(new Error("POS机号不能为空"));
        try {
          const res = await allApi.ecm.posDevice
            .verifyPosNoExits({
              posNo: value,
              merchantId: formData.value.merchantId,
            })
            .then((res) => {
              if (res.data) {
                callback();
              } else {
                callback(new Error("POS机号已被注册，请更换POS机号"));
              }
            });
          if (!res.data) callback(new Error("POS机号已被注册，请更换POS机号"));
          else callback();
        } catch (error) {
          callback(new Error("服务器异常"));
        }
      },
    },
  ],
  snNo: {
    type: "string",
    trigger: ["blur"],
    validator: (rule, value, callback) => {
      if (!trim(value).length) {
        callback(new Error("设备SN号不能为空"));
      } else {
        callback();
      }
    },
  },
});
onLoad(() => {
  getMerchanList();
  const info = commonStore.deviceInfo;
  formData.value.snNo = commonStore.snNo;
  formData.value.deviceModel = info.deviceModel;
  formData.value.deviceManufacturer = info.brand;
  formData.value.appVersion = info.appVersion;
  formData.value.sysVersion = info.romVersion;
  formData.value.homeScreen = `${info.windowWidth}x${info.windowHeight}`;
  formData.value.secondaryScreen = `${info.screenWidth}x${info.screenHeight}`;
});
const merchantList = ref([]);
async function getMerchanList() {
  const res = await allApi.merchant.getMerchantInfoList();
  console.log(res);
  merchantList.value = res.data;
}
const posNoSuccess = ref(false);
async function posNoBlur() {
  await formRef.value.validateField("posNo", (res) => {
    posNoSuccess.value = !res.length;
  });
}

async function submit() {
  utils.throttle(async () => {
    await formRef.value.validate();
    await allApi.ecm.posDevice.bindPosDevice(formData.value);

    useCommonStore().setPosNo(formData.value.posNo);
    useCommonStore().setSnNo(formData.value.snNo);
    utils.toUrl("/pages/index/index", "reLaunch");
  });
}
async function changeMerchantId(val) {
  console.log(val);
  formRef.value.validateField("merchantId");
  if (val) {
    const res = merchantList.value.find((item) => item.id == val.id);
    formData.value.merchantName = res?.name;
    formData.value.authId = res?.authId;
    console.log(formData.value);
    useCommonStore().setAuthId(res?.authId);
    useCommonStore().setMerchantId(res?.id);
    useCommonStore().setMerchantName(res?.name);
    if (formData.value.posNo) formRef.value.validateField("posNo");
  }
}
</script>
<style lang="scss" scoped>
.page-body {
  width: 1280px;
  height: 672px;
  background: url("../../static/images/bind_bg.png") no-repeat center;
  background-size: 100% 100%;
  touch-action: none; /* 防止滑动或双指缩放 */

  .submit_bt {
    width: 387px;
    height: 53.33px;
    font-size: 18px;
    font-weight: 500;
    background: #1b7afe;
    border-radius: 5px;
  }
  .content {
    padding: 33px 33px 47px;
    position: fixed;
    left: 680px;
    top: 133.33px;
    width: 453.33px;
    min-height: 433.33px;
    opacity: 1;
    border-radius: 13.33px;
    background: #ffffff;
    box-shadow: 0px 6.67px 20px 6.67px #000000;

    ::v-deep .u-form-item__body {
      padding: 0;
    }

    ::v-deep .u-form-item__body__right__message {
      // margin-left: 0!important;
      font-size: 16px;
      line-height: 1.2;
    }

    .title_text_img {
      width: 259px;
    }
  }
  .iconfont {
    color: $uni-text-color-disable;
    margin-right: 4px;
    width: 20px;
    height: 20px;
    line-height: 1;
    font-size: 20px;
  }
}

.pos-no-success {
  color: $uni-color-success;
  font-size: 16px;
}
</style>
